﻿#region Copyright © 2010 Chad Albrecht & Mark Adams
/*
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

/* © BLOKUS and associated trademarks are copyright Mattel, Inc.   */
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Blokus
{
    public partial class TileWell : UserControl
    {
        private List<Piece> pieces = new List<Piece>();
        double _lasttop = 0;

        private const int TURN_ZINDEX = 200;       

        #region Properties
        private double _tileSize = 50.0;
        /// <summary>
        /// What is the size of the individual tiles on each piece?
        /// </summary>
        public double TileSize
        {
            get { return _tileSize; }
            set { _tileSize = value; }
        }

        private Color _color = Colors.Purple;
        /// <summary>
        /// What is this player's color?
        /// </summary>
        public Color Color
        {
            get { return _color; }
            set { _color = value; }
        }

        private GameBoard _gameBoard = null;
        /// <summary>
        /// What instance of the gameboard is being used?
        /// </summary>
        public GameBoard gameBoard
        {
            get { return _gameBoard; }
            set 
            {
                _gameBoard = value;
                foreach (Piece p in pieces)
                {
                    p.gameBoard = _gameBoard;
                }
                _gameBoard.GameReset += new GameBoard.GameResetHandler(_gameBoard_GameReset);
            }
        }     

        private int _playerNumber = 0;
        /// <summary>
        /// What is this players number?
        /// </summary>
        public int PlayerNumber
        {
            get { return _playerNumber; }
            set { _playerNumber = value; }
        }

        private Piece _pieceBeingDragged = null;
        /// <summary>
        /// What piece is currently being dragged?
        /// </summary>
        public Piece PieceBeingDragged
        {
            get { return _pieceBeingDragged; }
            set { _pieceBeingDragged = value; }
        }

        private bool _isFirstMove = true;
        /// <summary>
        /// Is this this players first move?
        /// </summary>
        public bool IsFirstMove
        {
            get { return _isFirstMove; }
            set { _isFirstMove = value; }
        }

        private bool _isTurn = false;
        /// <summary>
        /// Is it this players turn?
        /// </summary>
        public bool IsTurn
        {
            get { return _isTurn; }
            set 
            {
                _isTurn = value;
                this.TurnIndicator.Visibility = _isTurn ? Visibility.Visible : Visibility.Collapsed;
            }
        }

        /// <summary>
        /// Return the current score for this player
        /// </summary>
        public int Score
        {
            get
            {
                int score = 0;
                foreach (Piece piece in pieces)
                {
                    if (!piece.Placed)
                        score -= piece.TileCount;
                }
                return score;
            }
        }
        /// <summary>
        /// Is this player dead?  (Can't place anymore pieces)
        /// </summary>
        public bool IsDead
        {
            get
            {
                bool isdead = true;
                if (this.IsFirstMove)
                {
                    isdead = false;                   
                }
                else
                {
                    foreach (Piece piece in pieces)
                    {
                        if (!piece.Placed)
                        {
                            if (this.gameBoard.PieceCanBePlaced(piece))
                            {
                                isdead = false;
                                break;
                            }
                        }
                    }
                }
                if (isdead)
                {
                    this.lblPlayer1.Foreground = new SolidColorBrush(Colors.Red);
                }
                return isdead;
            }
        }
        #endregion

        public delegate void TurnFinishedHandler(object sender);
        public event TurnFinishedHandler TurnFinished;
                
        public TileWell()
        {
            InitializeComponent();            

            CreatePieces();
            this.LayoutUpdated += new EventHandler(TileWell_LayoutUpdated);
            this.Loaded += new RoutedEventHandler(TileWell_Loaded);

            this.TurnIndicator.Visibility = Visibility.Collapsed;
        }
                        
       
        private void CreatePieces()
        {
            for (int i = 0; i < 256; i++)
            {
                Piece piece = BlokusPieceFactory.CreatePiece(i, this.Color, this);
                if (piece == null)
                    break;
                else
                {
                    piece.PiecePlaced += new Piece.PiecePlacedHandler(piece_PiecePlaced);

                    // TODO: Refactor this to remove hard coded values and 
                    // make more dynamic.
                    double left = -1;
                    double top = -1;

                    if ((i % 3) == 0)
                    {
                        left = 20;
                        top = (i * 35) + 20;
                        _lasttop = top;
                    }
                    else
                    {
                        left = (i % 3) * 90;
                        top = _lasttop;
                    }

                    Canvas.SetTop(piece, top);
                    Canvas.SetLeft(piece, left);
                    piece.OrigTopLeft = new Point(left, top);                 
                    this.WellCanvas.Children.Add(piece);
                    this.pieces.Add(piece);
                }           
                
            }
        }

        public void BringToTop()
        {
            Canvas.SetZIndex(this, TURN_ZINDEX);
        }
        public void SendToBack()
        {
            Canvas.SetZIndex(this, TURN_ZINDEX - 1 - this.PlayerNumber);
        }

        void piece_PiecePlaced(object sender)
        {
            if (TurnFinished != null)
                TurnFinished(sender);

            UpdatePlayerString();
        }

        bool Initialized = false;
        void TileWell_LayoutUpdated(object sender, EventArgs e)
        {
            if (!Initialized)
            {
                InitPieces();
                Initialized = true;
            }
        }

        void TileWell_Loaded(object sender, RoutedEventArgs e)
        {           
            UpdatePlayerString();
        }    

        private void InitPieces()
        {
            foreach (Piece piece in pieces)
            {                
                piece.TileSize = this.TileSize;
                piece.Color = this.Color;
                piece.PlayerNumber = this.PlayerNumber;
                piece.InitTiles();
            }
        }

        private void UpdatePlayerString()
        {
            this.lblPlayer1.Content = String.Format("Player {0} : {1} points", this.PlayerNumber + 1, this.Score);                        
        }

        /// <summary>
        /// Push a keypress into the control
        /// </summary>
        /// <param name="e">KeyEventArgs</param>
        public void KeyPress(KeyEventArgs e)
        {
            if (this.PieceBeingDragged != null)
                this.PieceBeingDragged.KeyPress(e);
        }

        /// <summary>
        /// Reset peices for game start
        /// </summary>
        private void _gameBoard_GameReset(object sender)
        {               
            foreach (Piece piece in pieces)
            {
                piece.InitTiles();
                piece.ResetToOriginalPosition();
                piece.Placed = false;
            }
            this.IsTurn = false;
            this.IsFirstMove = true;
            this.lblPlayer1.Foreground = new SolidColorBrush(Colors.White);
            UpdatePlayerString();
        }
        
    }
}
